//输入某二叉树的前序遍历和中序遍历的结果，请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 
//
// 
//
// 例如，给出 
//
// 前序遍历 preorder = [3,9,20,15,7]
//中序遍历 inorder = [9,3,15,20,7] 
//
// 返回如下的二叉树： 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7 
//
// 
//
// 限制： 
//
// 0 <= 节点个数 <= 5000 
//
// 
//
// 注意：本题与主站 105 题重复：https://leetcode-cn.com/problems/construct-binary-tree-from-
//preorder-and-inorder-traversal/ 
// Related Topics 树 递归 
// 👍 374 👎 0


//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private static final Map<Integer, Integer> inorderMap = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int lengthOfInOrder = inorder.length;
        for (int i = 0; i < lengthOfInOrder; i++) {
            inorderMap.put(inorder[i], i);
        }

        return this.myBuild(preorder, inorder, 0, lengthOfInOrder -1, 0, lengthOfInOrder - 1);
    }

    public TreeNode myBuild(int[] preorder, int[] inorder, int pre_left, int pre_right, int in_left, int in_right){
        if (pre_left > pre_right) return null;

        int pre_root = pre_left;
        int in_root = inorderMap.get(preorder[pre_root]);

        TreeNode rootNode = new TreeNode(preorder[pre_root]);

        int left_size = in_root - in_left;

        rootNode.left = myBuild(preorder, inorder, pre_left + 1, pre_left + left_size, in_left, in_root - 1);
        rootNode.right = myBuild(preorder, inorder, pre_left + left_size + 1, pre_right, in_root + 1, in_right);
        return rootNode;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
